package com.prex.auth.authentication.third;

import com.prex.auth.security.PrexUserDetailsServiceImpl;
import com.prex.auth.security.SocialUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @Classname ThirdAuthenticationSecurityConfig
 * @Description TODO
 * @Author Created by Lihaodong (alias:小东啊) im.lihaodong@gmail.com
 * @Date 2019-09-16 11:29
 * @Version 1.0
 */
@Component
public class ThirdAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private AuthenticationSuccessHandler hcloudAuthenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler hcloudAuthenticationFailureHandler;

    @Autowired
    private PrexUserDetailsServiceImpl userDetailsService;

    @Override
    public void configure(HttpSecurity builder) throws Exception {
        //配置Filter
        ThirdAuthenticationFilter thirdAuthenticationFilter = new ThirdAuthenticationFilter();
        //配置AuthenticationManager
        thirdAuthenticationFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        //配置
        thirdAuthenticationFilter.setAuthenticationSuccessHandler(hcloudAuthenticationSuccessHandler);
        thirdAuthenticationFilter.setAuthenticationFailureHandler(hcloudAuthenticationFailureHandler);
        ThirdAuthenticationProvider thirdAuthenticationProvider = new ThirdAuthenticationProvider();
        thirdAuthenticationProvider.setUserService(userDetailsService);
        //将自定义的AuthenticationProvider添加到AuthenticationManager所管理的Provider集合里面去
        builder.authenticationProvider(thirdAuthenticationProvider)
                //将过滤器添加到用户名密码验证过滤器的后面就行
                .addFilterAfter(thirdAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
